package com.oozol.lieluyun.controller;

import com.oozol.lieluyun.entity.BuildHistory;
import com.oozol.lieluyun.entity.BuildJob;
import com.oozol.lieluyun.entity.JobList;
import com.oozol.lieluyun.entity.ResultData;
import com.oozol.lieluyun.service.IJenkinsService;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JenkinsController {
   @Autowired
   private IJenkinsService jenkinsServices;

   @GetMapping({"/api/jenkins/jobList"})
   public ResultData<List<JobList>> jobList() throws Exception {
      List<JobList> jobList = this.jenkinsServices.jobList();
      ResultData res = new ResultData();
      res.setMsg("操作成功");
      res.setData(jobList);
      return res;
   }

   @GetMapping({"/api/jenkins/buildHistory"})
   public ResultData<List<BuildHistory>> buildHistory(String jobName) throws Exception {
      List<BuildHistory> jobDetails = this.jenkinsServices.buildHistory(jobName);
      ResultData res = new ResultData();
      res.setMsg("操作成功");
      res.setCount(jobDetails.size());
      res.setPage(1);
      res.setData(jobDetails);
      return res;
   }

   @GetMapping({"/api/jenkins/buildHistoryLog"})
   public ResultData<String> buildHistoryLog(String jobName, Integer number) throws Exception {
      String log = this.jenkinsServices.buildHistoryLog(jobName, number);
      ResultData res = new ResultData();
      res.setMsg("操作成功");
      res.setData(log);
      return res;
   }

   @PostMapping({"/api/jenkins/buildJob"})
   public ResultData<Integer> buildJob(@RequestBody BuildJob buildJob) throws Exception {
      Integer resStatus = this.jenkinsServices.buildJob(buildJob);
      ResultData res = new ResultData();
      res.setMsg("操作成功");
      res.setData(resStatus);
      return res;
   }

   @GetMapping({"/api/jenkins/gitTags"})
   public ResultData<List<String>> gitTags(String jobName) throws Exception {
      List<String> gitTagList = this.jenkinsServices.gitTags(jobName);
      ResultData res = new ResultData();
      res.setMsg("操作成功");
      res.setData(gitTagList);
      return res;
   }

   @RequestMapping(
      value = {"/api/jenkins"},
      method = {RequestMethod.GET}
   )
   public Object jenkinsTest() throws URISyntaxException, Exception {
      Date d = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
      String tagName = sdf.format(d);
      return tagName;
   }
}
